<template>
  <view class="home">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <image class="nav-logo" src="/static/logo.png" mode="aspectFit" />
      <text class="nav-title">辅导君</text>
      <view class="nav-user" @click="goProfile">
        <image class="user-avatar" src="/static/logo.png" mode="aspectFill" />
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-container">
      <swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#1e98d7">
        <swiper-item v-for="(banner, index) in banners" :key="index">
          <view class="banner-item" @click="onBannerClick(banner)">
            <image class="banner-image" :src="banner.image" mode="aspectFill" />
            <view class="banner-overlay">
              <text class="banner-title">{{ banner.title }}</text>
              <text class="banner-desc">{{ banner.desc }}</text>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 顶部tab -->
    <view class="tabs">
      <view v-for="(tab, idx) in tabs" :key="tab" :class="['tab', currentTab === idx ? 'active' : '']" @click="switchTab(idx)">{{ tab }}</view>
    </view>

    <!-- 导师卡片列表 -->
    <scroll-view class="tutor-list" scroll-y="true" :style="{ height: scrollHeight + 'px' }">
      <view class="tutor-card" v-for="(tutor, idx) in filteredTutors" :key="tutor.id || idx" @click="goTutorDetail(tutor)">
        <image class="avatar" :src="tutor.avatar || '/static/logo.png'" mode="aspectFill" />
        <view class="info">
          <view class="name-row">
            <text class="name">{{ tutor.nickname || tutor.name }}</text>
            <text v-if="tutor.verified" class="verified">已实名认证</text>
            <text v-else class="unverified">未实名认证</text>
          </view>
          <view class="school">{{ tutor.highestEducationSchool }} | {{ getEducationLevelText(tutor.educationLevel) }} | {{ tutor.major }}</view>
          <view class="stats">已辅导：{{ tutor.tutoringCount || 0 }}</view>
          <view class="desc">{{ tutor.selfIntroduction || tutor.experience }}</view>
          <view class="tags">
            <text v-for="tag in getGoodAtItemsText(tutor.goodAtItems)" :key="tag" class="tag">{{ tag }}</text>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && filteredTutors.length === 0" class="empty-state">
        <text class="empty-text">暂无相关导师</text>
      </view>
    </scroll-view>

    <!-- 悬浮发布按钮 -->
    <view class="fab" @click="goPublish">
      <text class="fab-text">+</text>
    </view>


  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useTutorStore } from '../../../store/tutor.js'
import { useUserStore } from '../../../store/user.js'
import { teacherApi, constants } from '../../../api'
import { handleApiResponse, formatTeacherData, handlePaginationData } from '../../../utils/apiHelper'

const tutorStore = useTutorStore()
const userStore = useUserStore()

const tabs = ref(['推荐', '高校讲师', '博士', '硕士', '本科'])
const currentTab = ref(0)
const scrollHeight = ref(600)
const loading = ref(false)
const teacherList = ref([])
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 标签页对应的学历筛选值
const tabEducationMap = {
  '推荐': null,
  '高校讲师': constants.TEACHER_LEVEL.PROFESSOR,
  '博士': constants.TEACHER_LEVEL.DOCTOR,
  '硕士': constants.TEACHER_LEVEL.MASTER,
  '本科': constants.TEACHER_LEVEL.UNDERGRADUATE
}

// 轮播图数据
const banners = ref([
  {
    id: 1,
    title: '优质师资推荐',
    desc: '小班课程、一对一辅导、案例推广、期刊合作等',
    image: '/static/banner1.jpg',
    url: ''
  },
  {
    id: 2,
    title: '专业学术指导',
    desc: '博士硕士在线答疑，助力学术提升',
    image: '/static/banner2.jpg',
    url: ''
  },
  {
    id: 3,
    title: '课程辅导服务',
    desc: '覆盖各个学科，个性化定制方案',
    image: '/static/banner3.jpg',
    url: ''
  }
])

// 根据当前tab筛选导师
const filteredTutors = computed(() => {
  return teacherList.value
})

// 加载教师列表
const loadTeacherList = async (isRefresh = false) => {
  if (loading.value) return

  loading.value = true

  const tabName = tabs.value[currentTab.value]
  const educationLevel = tabEducationMap[tabName]

  const params = {
    current: isRefresh ? 1 : pagination.value.current,
    size: pagination.value.size
  }

  // 如果不是推荐页面，添加学历筛选
  if (educationLevel) {
    params.educationLevel = educationLevel
  }

  const result = await handleApiResponse(
    teacherApi.getTeacherList(params),
    {
      showLoading: false, // 我们自己管理loading状态
      showError: true
    }
  )

  loading.value = false

  if (result.success) {
    const paginationData = handlePaginationData(
      { result: result.data },
      teacherList.value,
      isRefresh
    )

    // 格式化教师数据
    teacherList.value = paginationData.list.map(teacher => formatTeacherData(teacher))
    pagination.value = paginationData.pagination
  }
}

// 切换标签页
const switchTab = (index) => {
  if (currentTab.value === index) return

  currentTab.value = index
  pagination.value.current = 1
  teacherList.value = []
  loadTeacherList(true)
}

// 获取学历文本
const getEducationLevelText = (level) => {
  return constants.TEACHER_LEVEL_TEXT[level] || '未知'
}

// 获取擅长项目文本数组
const getGoodAtItemsText = (goodAtItems) => {
  if (!Array.isArray(goodAtItems)) return []
  return goodAtItems.map(item => constants.GOOD_AT_ITEMS_TEXT[item]).filter(Boolean)
}

const goPublish = () => {
  uni.navigateTo({ url: '/uniapp/pages/student/Publish' })
}

const goTutorDetail = (tutor) => {
  // 设置当前导师到store
  tutorStore.setCurrentTutor(tutor)
  uni.navigateTo({
    url: '/uniapp/pages/student/TutorDetail?tutorId=' + tutor.id
  })
}

const goProfile = () => {
  if (userStore.isLoggedIn) {
    uni.navigateTo({ url: '/uniapp/pages/student/Profile' })
  } else {
    uni.navigateTo({ url: '/uniapp/pages/student/Login' })
  }
}

// 轮播图点击事件
const onBannerClick = (banner) => {
  console.log('点击轮播图:', banner)
  // 这里可以根据banner的url进行页面跳转或其他操作
  if (banner.url) {
    uni.navigateTo({ url: banner.url })
  }
}



onMounted(() => {
  // 计算滚动区域高度
  const systemInfo = uni.getSystemInfoSync()
  scrollHeight.value = systemInfo.windowHeight - 280 // 减去导航栏、轮播图和tabbar高度

  // 加载初始数据
  loadTeacherList(true)
})
</script>

<style scoped>
.home {
  min-height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-logo {
  width: 48rpx;
  height: 48rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
}

.nav-user {
  width: 48rpx;
  height: 48rpx;
}

.user-avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: #eee;
}

/* 轮播图 */
.banner-container {
  background: #fff;
}

.banner-swiper {
  height: 320rpx;
}

.banner-item {
  position: relative;
  height: 100%;
  border-radius: 12rpx;
  margin: 0 24rpx;
  overflow: hidden;
}

.banner-image {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0,0,0,0.6));
  padding: 40rpx 32rpx 24rpx;
  color: #fff;
}

.banner-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
}

.banner-desc {
  font-size: 24rpx;
  opacity: 0.9;
  line-height: 1.4;
  display: block;
}

/* 标签页 */
.tabs {
  display: flex;
  flex-direction: row;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 24rpx 0 16rpx 0;
  color: #888;
  font-size: 28rpx;
  border-bottom: 4rpx solid transparent;
  position: relative;
}

.tab.active {
  color: #1e98d7;
  border-bottom: 4rpx solid #1e98d7;
  font-weight: bold;
}

/* 导师列表 */
.tutor-list {
  flex: 1;
  padding: 0 24rpx;
}

.tutor-card {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  margin-top: 24rpx;
  margin-bottom: 20rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  border: 1rpx solid #f0f0f0;
}

.avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  margin-right: 24rpx;
  background: #eee;
}

.info {
  flex: 1;
}

.name-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 8rpx;
}

.name {
  font-weight: bold;
  font-size: 32rpx;
  color: #333;
}

.verified {
  background: #ffe0a3;
  color: #b97a00;
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.unverified {
  background: #f0f0f0;
  color: #999;
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.school {
  color: #666;
  font-size: 26rpx;
  margin: 8rpx 0;
}

.stats {
  color: #999;
  font-size: 24rpx;
  margin: 4rpx 0 8rpx 0;
}

.desc {
  color: #999;
  font-size: 24rpx;
  margin-bottom: 12rpx;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.tags {
  display: flex;
  gap: 8rpx;
  flex-wrap: wrap;
}

.tag {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  background: #e3f2fd;
  color: #1976d2;
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 悬浮按钮 */
.fab {
  position: fixed;
  right: 40rpx;
  bottom: 180rpx;
  width: 112rpx;
  height: 112rpx;
  border-radius: 50%;
  background: #1e98d7;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 20rpx rgba(30, 152, 215, 0.3);
  z-index: 100;
}

.fab-text {
  color: #fff;
  font-size: 48rpx;
  font-weight: bold;
}


</style>